package com.ts.api.http.platform.biz;

import com.alibaba.fastjson.JSONObject;
import com.gitee.apanlh.util.algorithm.digest.MD5;
import com.gitee.apanlh.util.algorithm.encrypt.asymmetric.RSA;
import com.gitee.apanlh.util.base.ChooseEq;
import com.gitee.apanlh.util.base.Eq;
import com.gitee.apanlh.util.base.MapUtils;
import com.gitee.apanlh.util.dataformat.JsonUtils;
import com.gitee.apanlh.util.net.http.HttpRequestHeader;
import com.gitee.apanlh.util.valid.ValidParam;
import com.gitee.apanlh.web.model.vo.RequestVO;
import com.ts.api.common.util.H5DomainUrlUtils;
import com.ts.api.http.platform.entity.apply.ApiPlatApplyHuaRongFenQi;
import com.ts.api.http.platform.entity.dataexchange.ApiPlatDataExchangeHuaRongFenQi;
import com.ts.api.module.api.convert.core.entity.ApiApplyParameter;
import com.ts.api.module.api.convert.core.entity.ApiBizStatus;
import com.ts.api.module.api.convert.core.entity.ApiDataExchangeParameter;
import com.ts.api.module.api.convert.core.utils.ApiFieldConverter;
import com.ts.api.module.api.convert.platform.entity.RespPlatformNoticeApply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5Apply;
import com.ts.api.module.api.convert.platform.entity.RespPlatformPhoneMd5DataExchange;
import com.ts.api.module.api.convert.platform.handler.ApiPlatformPhoneMd5ConvertHandler;

import java.math.BigDecimal;
import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 华融分期
 *
 * @author ZJQ
 */
public class ApiPlatHuaRongFenQiPhoneMd5Convert implements ApiPlatformPhoneMd5ConvertHandler {
    public final String key;
    public final String publicKey;
    public final String code;

    public ApiPlatHuaRongFenQiPhoneMd5Convert(String key , String publicKey, String code) {
        this.key = key;
        this.publicKey = publicKey;
        this.code = code;
    }

    @Override
    public Object dataExchange(ApiDataExchangeParameter apiDataExchangeParameter) {
        String time = String.valueOf(System.currentTimeMillis());
        RSA rsa = new RSA(publicKey, null);
        String sign = rsa.encryptToBase64Str(time);
        //  设置请求头
        Map<String, String> dataMap = MapUtils.newHashMap(map -> {
            map.put("key", key);
            map.put("x-sign", sign);
            map.put("x-ts", time);
        });
        HttpRequestHeader httpRequestHeader = HttpRequestHeader.create(dataMap);
        apiDataExchangeParameter.setHttpRequestHeader(httpRequestHeader);

        ApiPlatDataExchangeHuaRongFenQi apiPlatDataExchangeHuaRongFenQi = new ApiPlatDataExchangeHuaRongFenQi();
        //  年龄
        apiPlatDataExchangeHuaRongFenQi.setAge(Integer.valueOf(apiDataExchangeParameter.getAge()));

        // loanAmount 预贷款额度
        String loanAmount = apiDataExchangeParameter.getLoanAmount();
        if (ValidParam.isNotEmpty(loanAmount)) {
            String money = ChooseEq.create()
                    .when(loanAmount, "1", "3")
                    .when(loanAmount, "2", "5")
                    .when(loanAmount, "3", "10")
                    .when(loanAmount, "4", "20")
                    .end();
            apiPlatDataExchangeHuaRongFenQi.setAppamt(money);
        }

        //  城市编码
        apiPlatDataExchangeHuaRongFenQi.setCityCode(apiDataExchangeParameter.getAreaCode());

        //  城市
        apiPlatDataExchangeHuaRongFenQi.setCityName(apiDataExchangeParameter.getCity());

        StringBuilder stringBuilder = new StringBuilder();
        //  信用记录-逾期记录
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getOverdue())) {
            String text = ChooseEq.create()
                    .when(apiDataExchangeParameter.getOverdue(), "1", "无逾期")
                    .when(apiDataExchangeParameter.getOverdue(), "2", "有逾期")
                    .when(apiDataExchangeParameter.getOverdue(), "3", "一年以内无逾期")
                    .end();
            stringBuilder.append("信用记录：").append(text).append(";").append("\n");
        }

        //  芝麻分
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getSesameCredit())) {
            String text = ChooseEq.create()
                    .when(apiDataExchangeParameter.getSesameCredit(), "1", "600分以下")
                    .when(apiDataExchangeParameter.getSesameCredit(), "2", "600~649分")
                    .when(apiDataExchangeParameter.getSesameCredit(), "3", "650~699分")
                    .when(apiDataExchangeParameter.getSesameCredit(), "4", "700分以上")
                    .end();
            stringBuilder.append("芝麻分：").append(text).append(";").append("\n");
        }

        //  职业
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getCareer())) {
            String text = ChooseEq.create()
                    .when(apiDataExchangeParameter.getCareer(), "1", "上班族")
                    .when(apiDataExchangeParameter.getCareer(), "2", "自由职业")
                    .when(apiDataExchangeParameter.getCareer(), "3", "企业主（有营业执照）")
                    .when(apiDataExchangeParameter.getCareer(), "4", "公务员或事业单位")
                    .end();
            stringBuilder.append("职业：").append(text).append(";").append("\n");
        }

        //  学历
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getEducationAttainment())) {
            String text = ChooseEq.create()
                    .when(apiDataExchangeParameter.getEducationAttainment(), "1", "初中及以下")
                    .when(apiDataExchangeParameter.getEducationAttainment(), "2", "中专")
                    .when(apiDataExchangeParameter.getEducationAttainment(), "3", "高中")
                    .when(apiDataExchangeParameter.getEducationAttainment(), "4", "大专")
                    .when(apiDataExchangeParameter.getEducationAttainment(), "5", "本科")
                    .when(apiDataExchangeParameter.getEducationAttainment(), "6", "研究生及以上")
                    .end();
            stringBuilder.append("学历：").append(text).append(";").append("\n");
        }

        //  收入形式
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getSalaryPayMethod())) {
            String text = ChooseEq.create()
                    .when(apiDataExchangeParameter.getSalaryPayMethod(), "1", "银行代发打卡")
                    .when(apiDataExchangeParameter.getSalaryPayMethod(), "2", "现金收入")
                    .when(apiDataExchangeParameter.getSalaryPayMethod(), "3", "个人转账")
                    .end();
            stringBuilder.append("收入形式：").append(text).append(";").append("\n");
        }

        //  客户类型
        String career = apiDataExchangeParameter.getCareer();
        if (ValidParam.isEmpty(career)) {
            //  无数据为个人用户
            stringBuilder.append("客户类型：").append("个人").append(";").append("\n");
        } else {
            String text = ChooseEq.create()
                    //  如果是企业就为企业用户
                    .when(career, "3", "企业")
                    //  个人用户
                    .end("个人");
            stringBuilder.append("客户类型：").append(text).append(";").append("\n");
        }

        //  房产情况
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getRealEstateInfo())) {
            String text = ChooseEq.create()
                    .when(apiDataExchangeParameter.getRealEstateInfo(), "1", "无")
                    .end("有");
            stringBuilder.append("房产情况：").append(text).append(";").append("\n");
        }

        //  车辆情况
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getCarInfo())) {
            String text = ChooseEq.create()
                    .when(apiDataExchangeParameter.getCarInfo(), "1", "无")
                    .end("有");
            stringBuilder.append("车辆情况：").append(text).append(";").append("\n");
        }

        //  保单
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getInsurancePolicy())) {
            String text = ChooseEq.create()
                    .when(apiDataExchangeParameter.getInsurancePolicy(), "1", "无")
                    .end("有");
            stringBuilder.append("保单：").append(text).append(";").append("\n");
        }

        //  社保
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getSocialSecurity())) {
            String text = ChooseEq.create()
                    .when(apiDataExchangeParameter.getSocialSecurity(), "1", "无")
                    .end("有");
            stringBuilder.append("社保：").append(text).append(";").append("\n");
        }

        //  公积金
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getProvidentFund())) {
            String text = ChooseEq.create()
                    .when(apiDataExchangeParameter.getProvidentFund(), "1", "无")
                    .end("有");
            stringBuilder.append("公积金：").append(text).append(";").append("\n");
        }

        //  银行代发
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getSalaryPayMethod())) {
            String text = ChooseEq.create()
                    .when(apiDataExchangeParameter.getSalaryPayMethod(), "1", "是")
                    .end("否");
            stringBuilder.append("银行代发：").append(text).append(";").append("\n");
        }
        //  客户描述
        apiPlatDataExchangeHuaRongFenQi.setCustDesc(stringBuilder.toString());
        //  ip地址
        apiPlatDataExchangeHuaRongFenQi.setCustIp(apiDataExchangeParameter.getIp());
        //  客户来源
        apiPlatDataExchangeHuaRongFenQi.setDomainFrom(code);
        //  姓名MD5
        if (ValidParam.isNotEmpty(apiDataExchangeParameter.getUserName())){
            apiPlatDataExchangeHuaRongFenQi.setName(MD5.create().digestToHex("浩安星"));
        }
        //  手机号MD5
        apiPlatDataExchangeHuaRongFenQi.setPhone(apiDataExchangeParameter.getPhoneMd5());

        // zhima 芝麻分:
        String sesameCredit = apiDataExchangeParameter.getSesameCredit();
        if (ValidParam.isNotEmpty(sesameCredit)) {
            String value = ChooseEq.create()
                    .when(sesameCredit, "1", "3")
                    .when(sesameCredit, "2", "0")
                    .when(sesameCredit, "3", "1")
                    .when(sesameCredit, "4", "2")
                    .end();
            apiPlatDataExchangeHuaRongFenQi.setSesameSeed(value);
        }

        // sex 性别 1男2女
        String sex = apiDataExchangeParameter.getSex();
        String sexChoose = ChooseEq.create()
                .when(sex, "0", "0")
                .when(sex, "1", "1")
                .end("3");
        apiPlatDataExchangeHuaRongFenQi.setSex(sexChoose);

        String json = JsonUtils.toJson(apiPlatDataExchangeHuaRongFenQi);
        return json;
    }


    @Override
    public Object apply(ApiApplyParameter apiApplyParameter) {
        String time = String.valueOf(System.currentTimeMillis());
        RSA rsa = new RSA(publicKey, null);
        String sign = rsa.encryptToBase64Str(time);
        //  设置请求头
        Map<String, String> dataMap = MapUtils.newHashMap(map -> {
            map.put("key", key);
            map.put("x-sign", sign);
            map.put("x-ts", time);
        });
        HttpRequestHeader httpRequestHeader = HttpRequestHeader.create(dataMap);
        apiApplyParameter.setHttpRequestHeader(httpRequestHeader);

        ApiPlatApplyHuaRongFenQi apiPlatApplyHuaRongFenQi = new ApiPlatApplyHuaRongFenQi();

        //  年龄
        apiPlatApplyHuaRongFenQi.setAge(Integer.valueOf(apiApplyParameter.getAge()));

        // loanAmount 预贷款额度
        String loanAmount = apiApplyParameter.getLoanAmount();
        if (ValidParam.isNotEmpty(loanAmount)) {
            String money = ChooseEq.create()
                    .when(loanAmount, "1", "3")
                    .when(loanAmount, "2", "5")
                    .when(loanAmount, "3", "10")
                    .when(loanAmount, "4", "20")
                    .end();
            apiPlatApplyHuaRongFenQi.setAppamt(money);
        }

        //  城市编码
        apiPlatApplyHuaRongFenQi.setCityCode(apiApplyParameter.getAreaCode());

        //  城市
        apiPlatApplyHuaRongFenQi.setCityName(apiApplyParameter.getCity());
        //  拓展信息
        ApiFieldConverter apiFieldConverter = ApiFieldConverter.create(apiApplyParameter);
        //  客户描述
        apiPlatApplyHuaRongFenQi.setCustDesc(apiFieldConverter.getExtendInfo());
        //  ip地址
        apiPlatApplyHuaRongFenQi.setCustIp(apiApplyParameter.getIp());
        //  客户授权协议
        List<String> authAgreement = new ArrayList<>();
        authAgreement.add(H5DomainUrlUtils.createUserProtocolUrl(apiApplyParameter.getProductPlanId(), apiApplyParameter.getPhoneMd5()));
        apiPlatApplyHuaRongFenQi.setCustomerAuths(authAgreement);
        //  客户来源
        apiPlatApplyHuaRongFenQi.setDomainFrom(code);
        //  姓名
        apiPlatApplyHuaRongFenQi.setName("浩安星");
        //  手机号
        apiPlatApplyHuaRongFenQi.setPhone(apiApplyParameter.getPhone());

        // zhima 芝麻分:
        String sesameCredit = apiApplyParameter.getSesameCredit();
        if (ValidParam.isNotEmpty(sesameCredit)) {
            String value = ChooseEq.create()
                    .when(sesameCredit, "1", "3")
                    .when(sesameCredit, "2", "0")
                    .when(sesameCredit, "3", "1")
                    .when(sesameCredit, "4", "2")
                    .end();
            apiPlatApplyHuaRongFenQi.setSesameSeed(value);
        }

        // sex 性别 1男2女
        String sex = apiApplyParameter.getSex();
        String sexChoose = ChooseEq.create()
                .when(sex, "0", "0")
                .when(sex, "1", "1")
                .end("3");
        apiPlatApplyHuaRongFenQi.setSex(sexChoose);
        String json = JsonUtils.toJson(apiPlatApplyHuaRongFenQi);
        return json;
    }

    @Override
    public RespPlatformPhoneMd5Apply respApply(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 0)) {
            return RespPlatformPhoneMd5Apply.ofFail();
        }
        return RespPlatformPhoneMd5Apply.ofSuc();
    }

    @Override
    public RespPlatformPhoneMd5DataExchange respDataExchange(String respJson) {
        JSONObject jsonObject = JsonUtils.get(respJson);
        if (jsonObject == null) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }
        if (!Eq.object(jsonObject.getInteger("code"), 0)) {
            return RespPlatformPhoneMd5DataExchange.ofFail();
        }

        JSONObject resData = JsonUtils.get(respJson).getJSONObject("data");
        JSONObject downStreamVO = resData.getJSONObject("downStreamVO");

        BigDecimal price = downStreamVO.getBigDecimal("unitPrice");
        String companyName = downStreamVO.getString("downstreamName");
        String productName = downStreamVO.getString("packageName");
        String logo = downStreamVO.getString("downstreamLogPath");

        RespPlatformPhoneMd5DataExchange result = RespPlatformPhoneMd5DataExchange.ofSuc();

        result.setPrice(price);
        result.setLogoPath(logo);
        result.setDisplayName(companyName);
        result.setProductName(productName);
        return result;
    }

    @Override
    public RespPlatformNoticeApply parseApplyNotice(RequestVO requestVO) {
        return null;
    }

    @Override
    public Map<String, Object> respApplyNotice(ApiBizStatus apiBizStatus) {
        return Map.of();
    }
}
